﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ExaminationSys.DataAccess;
using ExaminationSys.DataAccess.Entity;
using ExaminationSys.DataAccess.Repository;
using ExaminationSys.Helper;
using Ext.Net;

namespace ExaminationSys.View.Student
{
    public partial class JoinExamination : BasePage
    {
        private static readonly StudentTestHistoryService Proxy = ObjectFactory<StudentTestHistoryService>.Create();
        private static readonly StudentTestQuestionService ProxyQuestion = ObjectFactory<StudentTestQuestionService>.Create();
        private static readonly PaperInfoService ProxyPaper = ObjectFactory<PaperInfoService>.Create();
        private static readonly LoginLogService ProxyLLS = ObjectFactory<LoginLogService>.Create();
        private static readonly SubSectionDetailInfoService ProxySSD = ObjectFactory<SubSectionDetailInfoService>.Create();
        public static string questionList = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //zsd.Text = "display:none;";
                try
                {
                    if (Page.Request.QueryString["PaperID"] != null &&
                        (Page.Request.QueryString["sid"] != null || Page.Request.QueryString["stype"] != null))
                    {
                        string sid = string.Empty;
                        string stype = string.Empty;
                        sid = Page.Request.QueryString["sid"] ?? string.Empty;
                        stype = Page.Request.QueryString["stype"] ?? string.Empty;

                        base.ResetSession();

                        ExaminationSys.DataAccess.Entity.Student loginInfo = Session["StudentInfo"] as ExaminationSys.DataAccess.Entity.Student;
                        if (loginInfo == null || loginInfo.ID == null)
                        { Response.Redirect("~/StudyCenter.aspx"); }
                        else
                        {
                            studentID.Value = loginInfo.ID.ToString();
                            paperID.Value = Page.Request.QueryString["PaperID"];

                            if (!string.IsNullOrEmpty(sid))
                            {
                                #region

                                bool changed = base.CheckSectionId(sid);
                                if (changed)
                                {
                                    // Log
                                    LoginLog log = new LoginLog();
                                    log.ID = Guid.NewGuid();
                                    log.UserID = loginInfo.UserID;
                                    log.LoginTime = DateTime.Now;
                                    log.LoginType = (int)LoginType.已登录栏目;
                                    log.LastResourceID = sid;
                                    ProxyLLS.Insert(log);
                                }
                                else
                                {
                                    Response.Redirect("~/error.aspx");
                                }
                                #endregion
                            }

                            #region

                            // 生成题目
                            StudentPaperQuestion(paperID.Value.ToString(), studentID.Value.ToString());
                            // 试题类型
                            hidsectionid.Value = sid;

                            TestType(sid, stype);

                            var host = GetHost();
                            back1.HRef = host + "/StudyCenter.aspx";
                            back2.HRef = host + "/StudyCenter.aspx";

                            #endregion
                        }
                    }
                    else
                    { Response.Redirect("~/StudyCenter.aspx"); }
                }
                catch { }
            }
        }
        private void TestType(string sectionid, string stype)
        {
            if (!string.IsNullOrEmpty(sectionid)&&string.IsNullOrEmpty(stype))
            {
                var items = ProxySSD.GetListBySubSectionId(new Guid(sectionid));
                var ssi = items.FindAll(r => r.PaperID == new Guid(paperID.Value.ToString())).FirstOrDefault();
                if (ssi != null)
                {
                    if (ssi.KnowledgeType != 3)
                        btnSure.Visible = false;
                }
            }
            else if (!string.IsNullOrEmpty(sectionid) && !"2".Equals(stype))
            {
                btnSure.Visible = false;
            }
            else if ("2".Equals(stype))
            {
                btnSure.Visible = false;
            }
            if (btnSure.Visible)
                X.Js.Call("setShowHidden", "block");
        }

        private void StudentPaperQuestion(string paperid, string studentid)
        {
            PaperInfo paperInfo = ProxyPaper.Get(new Guid(paperid));
            if (paperInfo != null)
            {
                lblPaperTitle.Text = paperInfo.Title;
                var testhistoryid = Guid.NewGuid();
                List<StudentPaperQuestionAnswer> spqalist = Proxy.StudentPaper(paperid, studentid, ref testhistoryid);

                if (spqalist != null && spqalist.Count > 0)
                {
                    Session["sthid"] = testhistoryid.ToString() ;
                    sthID.Value = testhistoryid.ToString();
                    hidquestioncount.Value = spqalist.Count.ToString();
                    int showindex = 0;

                    //bool visible = false;
                    ////txtindex.Value = spqalist.Count.ToString();
                    ////questionvp.InnerText = "";
                    //foreach (StudentPaperQuestionAnswer spqa in spqalist)
                    //{
                    //    if (showindex == 0 && string.IsNullOrEmpty(spqa.studentPaperQuestion.StudentAnswer))
                    //    {
                    //        showindex = spqa.questionindex; break;
                    //    }
                    //}
                    //showindex = showindex == 0 ? spqalist.Count : showindex;
                    //foreach (StudentPaperQuestionAnswer spqa in spqalist)
                    //{
                    //    visible = showindex == spqa.questionindex;
                    //    StudentPaperTest(spqa.listDBAnswer, spqa.studentPaperQuestion, spqa.questionindex, visible);
                    //}
                    //if (!IsPostBack)
                    //    txtindex.Value = showindex.ToString();

                    questionlistdiv.InnerHtml = Proxy.BuildQuestionList(spqalist, ref showindex, GetHost());
                    //questionlistdiv.InnerHtml = questionList;
                    txtindex.Value = showindex.ToString();
                }
                else
                {
                    btnNextQuestion.Visible = false;
                    btnSure.Visible = false;
                    MessageBoxHelper.ShowWarning("获取不到相关题目，请咨询管理员！");
                    return;
                }
            }
        }
        private void StudentPaperTest(List<DBAnswer> list, StudentPaperQuestion spd, int rowindex,bool visible)
        {
            System.Web.UI.WebControls.Panel pl = this.AllPanel;
            StringBuilder subplname = new StringBuilder("");
            System.Web.UI.WebControls.Panel subpl = new System.Web.UI.WebControls.Panel();
            subpl.ID = "questionPanel" + rowindex.ToString();
            subpl.Visible = visible;

            if (spd.SubjectType.Equals("视听"))
            {
                var host = GetHost();
                //System.Web.UI.WebControls.HyperLink hl = new System.Web.UI.WebControls.HyperLink();
                //hl.NavigateUrl = String.Format("{0}/View/Student/JoinExaminationMMShow.aspx?mvurl={1}", host, spd.AttachFile);
                ////hl.Icon = Icon.FilmStart;
                //hl.ImageUrl = host + "/images/mv.jpg";
                //hl.Target = "_blank";
                //hl.Text = "视频/MP3";
                //hl.CssClass = "mv";
                //subpl.Controls.Add(hl);
                Literal hl = new Literal();
                hl.Text = "<object id=\"player\" height=\"64\" width=\"360\" classid=\"CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6\">  ";
                hl.Text += "<param name=\"AutoStart\" VALUE=\"0\">  ";
                hl.Text += "<param name=\"Balance\" VALUE=\"0\">  ";
                hl.Text += "<param name=\"enabled\" value=\"-1\">  ";
                hl.Text += "<param name=\"EnableContextMenu\" VALUE=\"-1\">  ";
                hl.Text += "<param name=\"url\" value=\"" + String.Format("{0}/View/Student/Audio.ashx?mvurl={1}", host, spd.AttachFile) + "\">  ";
                hl.Text += "<param name=\"PlayCount\" VALUE=\"1\">  ";
                hl.Text += "<param name=\"rate\" value=\"1\">  ";
                hl.Text += "<param name=\"currentPosition\" value=\"0\">  ";
                hl.Text += "<param name=\"currentMarker\" value=\"0\">  ";
                hl.Text += "<param name=\"defaultFrame\" value=\"\">  ";
                hl.Text += "<param name=\"invokeURLs\" value=\"0\">  ";
                hl.Text += "<param name=\"baseURL\" value=\"\">  ";
                hl.Text += "<param name=\"stretchToFit\" value=\"0\">  ";
                hl.Text += "<param name=\"volume\" value=\"50\">  ";
                hl.Text += "<param name=\"mute\" value=\"0\">  ";
                hl.Text += "<param name=\"uiMode\" value=\"mini\">  ";
                hl.Text += "<param name=\"windowlessVideo\" value=\"0\">  ";
                hl.Text += "<param name=\"fullScreen\" value=\"0\">  ";
                hl.Text += "<param name=\"enableErrorDialogs\" value=\"-1\">  ";
                hl.Text += "<param name=\"SAMIStyle\" value>  ";
                hl.Text += "<param name=\"SAMILang\" value>";
                hl.Text += "<param name=\"SAMIFilename\" value>  ";
                hl.Text += "</object><br/>&nbsp;<br/>";
                subpl.Controls.Add(hl);
            }

            if ("dbsubject".Equals(spd.PQuestionType.ToString()))
            {
                System.Web.UI.WebControls.Panel subject = new System.Web.UI.WebControls.Panel();
                Literal hsj = new Literal();
                subject.CssClass = "main985-top subjec_a";
                hsj.Text = string.Format("<span class=\"ico\" onclick=\"showSubject('{0}','{1}');\">点击显示大题内容</span>",
                    spd.STQID, spd.STitle ?? "");
                subject.Controls.Add(hsj);
                subpl.Controls.Add(subject);
            }

            //System.Web.UI.WebControls.Label df = new System.Web.UI.WebControls.Label();
            //df.Text = String.Format("{0}.  {1}", rowindex, spd.Content);
            //df.CssClass = "subject";
            //subpl.Controls.Add(df);
            Literal hdf = new Literal();
            hdf.Text = string.Format("<div class=\"subject\"><div class=\"subjectprefix\">{0}.  </div><ul>{1}</ul></div>", rowindex, spd.Content);
            subpl.Controls.Add(hdf);
            

            if (spd.QuestionType.Equals("多选"))
            {
                subplname.Append("2");
                foreach (DBAnswer dBanswer in list)
                {
                    #region 多选

                    System.Web.UI.WebControls.Panel answerpl = new System.Web.UI.WebControls.Panel();
                    answerpl.CssClass = "plq";
                    System.Web.UI.WebControls.CheckBox chk = new System.Web.UI.WebControls.CheckBox();
                    System.Web.UI.WebControls.Label df1 = new System.Web.UI.WebControls.Label();
                    System.Web.UI.WebControls.Label df2 = new System.Web.UI.WebControls.Label();

                    chk.ID = String.Format("{0}_chk_{1}_{2}",
                        dBanswer.Prefix.Trim(), dBanswer.ID, rowindex);//_{2}_{3} spd.StudentTestQuestionID, dBanswer.ID, spd.TestHistoryID);
                    chk.CssClass = "chkrad";
                    if (spd.StudentTestHistoryStatus != null && spd.StudentTestHistoryStatus == -1)
                    {
                        chk.Checked = string.IsNullOrEmpty(spd.StudentAnswer) ? false : spd.StudentAnswer.Contains(dBanswer.Prefix.Trim());
                    }
                    chk.ToolTip = dBanswer.Prefix.Trim();
                    subplname.AppendFormat("/{0}", chk.ID);

                    df1.Text = dBanswer.Prefix.Trim();
                    df1.CssClass = "prefix";
                    df2.Text = dBanswer.Content;
                    df2.CssClass = "subjectanswer";

                    answerpl.Controls.Add(chk);
                    answerpl.Controls.Add(df1);
                    answerpl.Controls.Add(df2);
                    subpl.Controls.Add(answerpl);

                    #endregion
                }
            }
            else
            {
                int radchecked = 0;
                subplname.Append("1");
                foreach (DBAnswer dBanswer in list)
                {
                    #region 单选

                    System.Web.UI.WebControls.Panel answerpl = new System.Web.UI.WebControls.Panel();
                    answerpl.CssClass = "plq";
                    System.Web.UI.WebControls.RadioButton rad = new System.Web.UI.WebControls.RadioButton();
                    System.Web.UI.WebControls.Label df1 = new System.Web.UI.WebControls.Label();
                    System.Web.UI.WebControls.Label df2 = new System.Web.UI.WebControls.Label();
                    rad.ID = String.Format("{0}_rad_{1}_{2}",
                        dBanswer.Prefix.Trim(), dBanswer.ID, rowindex);
                       // spd.StudentTestQuestionID, dBanswer.ID, spd.TestHistoryID, 
                    rad.GroupName = "rad_" + spd.StudentTestQuestionID.ToString();
                    rad.CssClass = "chkrad";
                    rad.ToolTip = dBanswer.Prefix.Trim();
                    subplname.AppendFormat("/{0}", rad.ID);
                    if (spd.StudentTestHistoryStatus != null && spd.StudentTestHistoryStatus == -1 && radchecked == 0)
                    {
                        rad.Checked = string.IsNullOrEmpty(spd.StudentAnswer) ? false : spd.StudentAnswer.Contains(dBanswer.Prefix.Trim());
                        if (rad.Checked)
                            radchecked = 1;
                    }
                    df1.Text = dBanswer.Prefix;
                    df1.CssClass = "prefix";
                    df2.Text = dBanswer.Content;
                    df2.CssClass = "subjectanswer";

                    answerpl.Controls.Add(rad);
                    answerpl.Controls.Add(df1);
                    answerpl.Controls.Add(df2);
                    subpl.Controls.Add(answerpl);

                    #endregion
                }
            }

            System.Web.UI.WebControls.Label lbl = new System.Web.UI.WebControls.Label();
            lbl.ID = "lblq" + rowindex.ToString();
            lbl.ToolTip = spd.StudentTestQuestionID.ToString();
            lbl.Text = subplname.ToString();
            lbl.Visible = false;
            subpl.Controls.Add(lbl);

            pl.Controls.Add(subpl);
        }

        protected void Next_Click(object sender, EventArgs e)
        {
            int index = int.Parse(txtindex.Value);
            int all = int.Parse(hidquestioncount.Value);

            System.Web.UI.WebControls.Panel subpl = this.FindControl("questionPanel" + index.ToString()) as System.Web.UI.WebControls.Panel;
            System.Web.UI.WebControls.Label lbl = this.FindControl("lblq" + index.ToString()) as System.Web.UI.WebControls.Label;

            string temp = string.Empty;
            if (subpl != null && lbl != null)
            {
                string name = lbl.Text;
                if (!btnSure.Visible && name != null && name.Length > 2)
                {
                    string stqid = lbl.ToolTip;
                    temp = AddAnswer(name, stqid, subpl);
                    if (string.IsNullOrEmpty(temp))
                    {
                        MessageBoxHelper.ShowWarning("答案提交失败！");
                        return;
                    }
                }
            }
            else
            {
                MessageBoxHelper.ShowWarning("获取不到下一题，请联系管理员！");
                return;
            }
            if (index < all)
            {
                index += 1;
                subpl.Visible = false;
                System.Web.UI.WebControls.Panel subpl2 = this.FindControl("questionPanel" + index.ToString()) as System.Web.UI.WebControls.Panel;
                subpl2.Visible = true;
                txtindex.Value = index.ToString();
                //
                //zsd.Text = "display:none;";
                imgDefaultResult.Visible = true;
                imgErrorResult.Visible = false;
                imgRightResult.Visible = false;
                txtknowledge.Visible = false;
                X.Js.Call("setKonledge", "");
            }
            if (index == all)
            {
                this.btnNextQuestion.Enabled = false;
                btnNextQuestion.ForeColor = System.Drawing.Color.Gray;
            }
            if (!string.IsNullOrEmpty(temp) && index == all)
            {
                Finished(1);
            }
        }
        protected void Sure_Click(object sender, EventArgs e)
        {
            int index = int.Parse(txtindex.Value);
            int all = int.Parse(hidquestioncount.Value);

            if (index <= all)
            {
                System.Web.UI.WebControls.Panel allpanel = this.AllPanel;
                System.Web.UI.WebControls.Panel subpl = allpanel.FindControl("questionPanel" + index.ToString()) as System.Web.UI.WebControls.Panel;
                System.Web.UI.WebControls.Label lbl = allpanel.FindControl("lblq" + index.ToString()) as System.Web.UI.WebControls.Label;

                if (subpl != null && lbl != null)
                {
                    string name = lbl.Text;
                    if (name != null && name.Length > 2)
                    {
                        string stqid = lbl.ToolTip;
                        string temp = AddAnswer(name, stqid, subpl);
                        if (!string.IsNullOrEmpty(temp))
                            AnswerCheck(stqid);
                    }
                    else
                        MessageBoxHelper.ShowWarning("没有找到答案！");
                }
                else
                {
                    MessageBoxHelper.ShowWarning("获取不到下一题，请联系管理员！");
                    return;

                }
                if (index == all)
                {
                    btnSure.ForeColor = System.Drawing.Color.Gray;
                    btnSure.Enabled = false;
                    Finished(0);
                }
            }
        }

        protected void Next_Click2(object sender, EventArgs e)
        {
            if ("完 成".Equals(btnNextQuestion.Text))
                Response.Redirect("~/StudyCenter.aspx");

            int index = int.Parse(txtindex.Value);
            int all = int.Parse(hidquestioncount.Value);

            string temp = string.Empty;
            if (!btnSure.Visible)
            {
                string stqid = stqidValue.Value;
                string stqanswer = stqanswerValue.Value;
                if (stqanswer != null && stqanswer.Length > 0)
                {                    
                    temp = AddAnswer2(stqid, stqanswer);
                    if (string.IsNullOrEmpty(temp))
                    {
                        X.Js.Call("showquestion", index);
                        return;
                    }
                }
                else
                {
                    MessageBoxHelper.ShowWarning("没有选择答案！");
                    X.Js.Call("showquestion", index);
                    return;
                }
            }
            if (index == all)
            {
                this.btnNextQuestion.Enabled = false;
                btnNextQuestion.ForeColor = System.Drawing.Color.Gray;
                btnNextQuestion.Text = "完 成";
            }
            if (!string.IsNullOrEmpty(temp) && index == all)
            {
                Finished(1);
            }
            if (index < all)
            {
                index += 1;
                txtindex.Value = index.ToString();

                imgDefaultResult.Visible = true;
                imgErrorResult.Visible = false;
                imgRightResult.Visible = false;
                txtknowledge.Visible = false;
                X.Js.Call("setKonledge", "");
                X.Js.Call("showquestion", index);
            }
        }
        protected void Sure_Click2(object sender, EventArgs e)
        {
            int index = int.Parse(txtindex.Value);
            int all = int.Parse(hidquestioncount.Value);
            string stqanswer = stqanswerValue.Value;
            
            if (index <= all)
            {
                string stqid = stqidValue.Value;
                if (stqanswer != null && stqanswer.Length > 0)
                {
                    string temp = AddAnswer2(stqid, stqanswer);
                    if (!string.IsNullOrEmpty(temp))
                        AnswerCheck(stqid);
                }
                else
                {
                    MessageBoxHelper.ShowWarning("没有选择答案！");
                    X.Js.Call("showquestion", index);
                    return;
                }

                if (index == all)
                {
                    if (imgRightResult.Visible)
                    {
                        btnSure.ForeColor = System.Drawing.Color.Gray;
                        btnSure.Enabled = false;
                    }
                    Finished(0);
                }
            }
            X.Js.Call("showquestion", index);
            X.Js.Call("showselectedanser", index, stqanswer);
        }

        private string GetHost()
        {
            var host = "http://" + HttpContext.Current.Request.Url.Host;
            var portflag = HttpContext.Current.Request.Url.IsDefaultPort;
            host += portflag ? "" : (":" + HttpContext.Current.Request.Url.Port);

            return host;
        }

        private void Finished(int actionflag)
        {
            #region 是否答题完成

            if (sthID.Value != null)
            {
                string[] list = ProxyQuestion.ResultUpdate(sthID.Value, hidsectionid.Value, actionflag);
                if (actionflag == 1 && list != null && list.Length > 0)
                {
                    lblscore.Text = list[0];
                    lblscoremessage.Text = list[3];
                    lblRightQuestion.Text = list[1];
                    lblErrorQuestion.Text = list[2];

                    CreateChartData();

                    //X.Js.Call("setKonledge", "");
                    this.questionvp.Visible = false;
                    this.resultvp.Visible = true;
                    this.btnSure.Enabled = false;
                    this.btnNextQuestion.Enabled = false;
                }
            }
            else
                MessageBoxHelper.ShowWarning("请选择答案！");

            #endregion
        }

        private void AnswerCheck(string stqid)
        {
            #region 答案是否正确

            // 知识点
            string knowledge = ProxyQuestion.GetQuestionKnowledge(stqid);
            List<SubSectionDetailInfo> items = ProxySSD.GetRelatedKnowledgeKeyWords(knowledge);
            StringBuilder sb = new StringBuilder("");
            int endposition = items == null ? -1 : (items.Count > 4 ? 4 : items.Count);
            var host = GetHost();
            for (int i = 0; i < endposition; i++)
            {
                sb.AppendFormat("<p><span>{1}</span><a href='{2}/LearningDetail.aspx?id={0}' target='_blank'>  [点击进入学习]</a></p>",
                    items[i].ID, items[i].Name, host);
            }
            txtknowledge.Visible = true;
            X.Js.Call("setKonledge", sb.ToString());

            bool isRight = ProxyQuestion.AnswerCheck(stqid);
            imgDefaultResult.Visible = false;
            imgErrorResult.Visible = false;
            imgRightResult.Visible = false;

            //zsd.Text = "";
            if (isRight)
                imgRightResult.Visible = true;
            else
                imgErrorResult.Visible = true;

            #endregion
        }

        private string AddAnswer(string name, string stqid, System.Web.UI.WebControls.Panel subpl)
        {
            #region 获取答案

            string result = string.Empty;
            string studenquestionanswer = string.Empty;
            string[] listid = name.Split('/');
            if (listid != null && listid.Length > 1)
            {
                if (listid[0].Equals("1"))
                {
                    #region 单选
                    for (int i = 1; i < listid.Length; i++)
                    {
                        try
                        {
                            System.Web.UI.WebControls.RadioButton rad = subpl.FindControl(listid[i]) as System.Web.UI.WebControls.RadioButton;
                            if (rad != null && rad.Checked)
                            {
                                studenquestionanswer = rad.ToolTip.Trim();
                                break;
                            }
                        }
                        catch { }
                    }
                    #endregion
                }
                else if (listid[0].Equals("2"))
                {
                    #region 多选
                    for (int i = 1; i < listid.Length; i++)
                    {
                        try
                        {
                            System.Web.UI.WebControls.CheckBox chk = subpl.FindControl(listid[i]) as System.Web.UI.WebControls.CheckBox;
                            if (chk != null && chk.Checked)
                                studenquestionanswer += chk.ToolTip.Trim();
                        }
                        catch { }
                    }
                    #endregion
                }
                else
                {
                    MessageBoxHelper.ShowWarning("请选择答案！");
                    return result;
                }
                if (string.IsNullOrEmpty(studenquestionanswer))
                {
                    MessageBoxHelper.ShowWarning("请选择答案！");
                    return result;
                }
                var success = ProxyQuestion.UpdateStudentAnwser(stqid, studenquestionanswer);
                if (success)
                    return "sucess";
            }
            else
            {
                MessageBoxHelper.ShowWarning("没有找到答案！");
                return result;
            }
            return result;

            #endregion
        }
        private string AddAnswer2(string stqid, string answer)
        {
            #region 获取答案

            string result = string.Empty;
            if (answer != null && answer.Length > 0)
            {
                var success = ProxyQuestion.UpdateStudentAnwser(stqid, answer);
                if (success)
                    return "sucess";
                else
                    MessageBoxHelper.ShowWarning("答案提交失败！");
            }
            else
                MessageBoxHelper.ShowWarning("请选择答案！");
            return result;

            #endregion
        }

        #region 图表数据获取
        /// <summary>
        /// 图表数据获取类
        /// </summary>
        public void CreateChartData()
        {

            List<ChartData> list = new List<ChartData>();
            ExaminationSys.DataAccess.Entity.Student loginInfo = Session["StudentInfo"] as ExaminationSys.DataAccess.Entity.Student;
            list = Proxy.GetTestHistoryChartData(loginInfo.ID);

            if (list == null)
            {
                list.Add(new ChartData { Name = "无测试记录", DataValue = 0 });
            }
            Store2.DataSource = list;
            Store2.DataBind();

        }
        #endregion
    }
}